package net.zhengxinyun.performance.controller.incentive;


import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.IncentiveFilter;
import net.zhengxinyun.performance.filter.IncentiveTypeFilter;
import net.zhengxinyun.performance.service.exportService.ExportService;
import net.zhengxinyun.performance.service.incentive.IncentiveService;
import net.zhengxinyun.performance.service.incentive.IncentiveTypeSerice;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.TokenService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: hyp
 * @Date: 2018/11/4 15:24
 */
@RestController
@RequestMapping("/incentive")
public class IncentiveController {

    private IncentiveService incentiveService;
    private TokenService tokenService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private IncentiveTypeSerice typeSerice;

    @Autowired
    private ExportService exportService;

    @Autowired
    public IncentiveController(IncentiveService incentiveService, TokenService tokenService) {
        this.incentiveService = incentiveService;
        this.tokenService = tokenService;
    }

    @PostMapping("/delete")
    public Result<String> delete(@RequestBody IncentiveParam incentiveParam) {
        if (tokenService.compareToken(incentiveParam.tokenEntity.getValue())) {
            String str = incentiveService.delete(incentiveParam.incentiveEntity);
            if (!"删除成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }

    @RequestMapping("/update")
    public Result<String> update(@RequestBody IncentiveParam incentiveParam) {
        if (tokenService.compareToken(incentiveParam.tokenEntity.getValue())) {
            String str = incentiveService.update(incentiveParam.incentiveEntity);
            if (!"修改成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }

    @PostMapping("/insert")
    public Result<String> insert(@RequestBody IncentiveParam incentiveParam) {
        if (tokenService.compareToken(incentiveParam.tokenEntity.getValue())) {

            UserEntity user = loginService.getUserByToken(incentiveParam.tokenEntity);
         //   List<Long> listItems = incentiveParam.incentiveEntity.getTypeItemId();

           // incentiveParam.incentiveEntity.setPointsType(itemIds);
            incentiveParam.incentiveEntity.setDepartCode(user.getDepartcode());
            String str = incentiveService.insert(incentiveParam.incentiveEntity);
            if (!"添加成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }

    @PostMapping("/query")
    public Result<HashMap<String, Object>> query(@RequestBody IncentiveParam incentiveParam,HttpServletRequest request) {
        if (tokenService.compareToken(incentiveParam.tokenEntity.getValue())) {
            //表2 查看全县所有正向激励
            if(!"2".equals(incentiveParam.incentiveFilter.getTable()))
            {
                UserEntity userEntity = loginService.getUserByToken(incentiveParam.tokenEntity);
                if(!"admin".equals(userEntity.getUserPermissions())){
                    incentiveParam.incentiveFilter.setDepartCode(userEntity.getDepartcode());
                    incentiveParam.incentiveFilter.setAudit("1");
                }

            }

            HashMap<String, Object> map = new HashMap<>();
            List<Map<String, Object>> list = incentiveService.query(incentiveParam.incentiveFilter);
            if (list.size() == 0) {
                incentiveParam.incentiveFilter.setPageNumber(incentiveParam.incentiveFilter.getPageNumber() - 1);
                list = incentiveService.query(incentiveParam.incentiveFilter);
            }
            Double total = Util.intGetTotalPage(incentiveService.queryForCount(incentiveParam.incentiveFilter), incentiveParam.incentiveFilter.getPageSize());
            map.put("list", list);
            map.put("total", total);

            // 获取所有加分类别 大类
            String year = (String) request.getSession().getAttribute("currentYear");
            if(year==null)
            {
                return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
            }


            List<IncentiveTypeFilter> liteType = typeSerice.queryType(new IncentiveTypeEntity(year));
            map.put("listType",liteType);

            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/pass")
    public Result<String> pass(@RequestBody IncentiveParam incentiveParam) {
        if (tokenService.compareToken(incentiveParam.tokenEntity.getValue())) {
            String str = incentiveService.pass(incentiveParam.incentiveEntity);
            if (!"审核成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/noPass")
    public Result<String> noPass(@RequestBody IncentiveParam incentiveParam) {
        if (tokenService.compareToken(incentiveParam.tokenEntity.getValue())) {
            String str = incentiveService.noPass(incentiveParam.incentiveEntity);
            if (!"回退成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/audit")
    public Result<HashMap<String,Object>> queryForAudit(@RequestBody IncentiveParam incentiveParam) {
        if (tokenService.compareToken(incentiveParam.tokenEntity.getValue())) {
            HashMap<String, Object> map = new HashMap<>();
            incentiveParam.incentiveFilter.setAudit("0");
            List<Map<String, Object>> list = incentiveService.query(incentiveParam.incentiveFilter);
            if (list.size() == 0) {
                incentiveParam.incentiveFilter.setPageNumber(incentiveParam.incentiveFilter.getPageNumber() - 1);
                list = incentiveService.query(incentiveParam.incentiveFilter);
            }
            Double total = Util.intGetTotalPage(incentiveService.queryForAuditCount(incentiveParam.incentiveFilter), incentiveParam.incentiveFilter.getPageSize());
            map.put("list", list);
            map.put("total", total);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/pointType")
    public Result<HashMap<String,Object>> pointType(@RequestBody IncentiveParam incentiveParam){
        List<IncentiveFilter> pointList;
        if (StringUtils.isNotBlank(incentiveParam.incentiveFilter.getDateTime())){
            pointList = incentiveService.queryGroupType(incentiveParam.incentiveFilter.getDateTime());
        }else {
            pointList = incentiveService.queryGroupType("");
        }
        List<IncentiveFilter> monthList;
        if (StringUtils.isNotBlank(incentiveParam.incentiveFilter.getDateTime())){
            monthList = incentiveService.queryGroupMonth(incentiveParam.incentiveFilter.getDateTime());
        }else {
            monthList = incentiveService.queryGroupMonth("");
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("pointType",pointList);
        map.put("monthType",monthList);
        return ResultUtils.getSuccessResults(map);
    }

   /* @PostMapping("/monthType")
    public Result<ArrayList<IncentiveFilter>> monthType(@RequestBody IncentiveParam incentiveParam){
        List<IncentiveFilter> list;
        if (StringUtils.isNotBlank(incentiveParam.incentiveFilter.getDateTime())){
            list = incentiveService.queryGroupMonth(incentiveParam.incentiveFilter.getDateTime());
        }else {
            list = incentiveService.queryGroupMonth("");
        }
        return ResultUtils.getSuccessResultList(list);
    }*/

   //联动下拉二级
     @PostMapping("/getItemList")
    public Result<ArrayList<IncentiveTypeItemEntity>> getItemList(@RequestBody IncentiveParam param){
        List<IncentiveFilter> list;

         String pointsType = param.incentiveFilter.getPointsType();
         if(StringUtils.isBlank(pointsType))
         {
             return ResultUtils.getResults(Result.Status.ERROR,"类别Id为空",null);
         }

         List<IncentiveTypeItemEntity> listItem = typeSerice.queryItems(new Long(pointsType));

         return ResultUtils.getSuccessResultList(listItem);
    }


    /**
     * 导出正向激励
     *
     * @param reponse
     */
    @GetMapping("/exportIncentive")
    public Result<String>  exprotCityIndexDate(HttpServletResponse reponse, HttpServletRequest request)
    {

        String year = (String) request.getSession().getAttribute("currentYear");
        if(year==null)
        {
            return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
        }


       Workbook cityIndexDate = exportService.exportIncentive(year);

        OutputStream out = null;

        try {
            out=reponse.getOutputStream();
            String fileName  = "正向激励汇总表.xls";
            reponse.setContentType("application/x-msdownload");
            reponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            cityIndexDate.write(out);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  ResultUtils.getSuccessResults();
    }

}

class IncentiveParam {
    public TokenEntity tokenEntity;
    public IncentiveFilter incentiveFilter;
    public IncentiveEntity incentiveEntity;
}
